<template>
  <div>
    <el-tree
      ref="tree"
      node-key="id"
      :data="list"
      :props="{ label: 'name' }"
      :show-checkbox="true"
      default-expand-all
      :check-strictly="true"
    />
    <div style="text-align: right;">
      <el-button @click="hCancel">取消</el-button>
      <el-button type="primary" @click="hSubmit">确定</el-button>
    </div>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permisson'
import { tranListToTreeData } from '@/utils/index'
import { getRoleDetail, assignPerm } from '@/api/settings'

export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.loadPermissionList()
    this.loadPermissionByRoleId()
  },
  methods: {
    //   获取用户已有的权限
    async loadPermissionByRoleId() {
      try {
        const res = await getRoleDetail(this.roleId)
        console.log('已有的权限', res)
        // 让复选框选中已有的权限
        this.$refs.tree.setCheckedKeys(res.data.permIds)
      } catch (err) {
        console.log(err)
      }
    },
    //   获取权限列表
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log('权限列表数据', res)
        this.list = tranListToTreeData(res.data)
      } catch (err) {
        console.log(err)
      }
    },
    hCancel() {
      this.$emit('close')
      // 清空当前的选择
      this.$refs.tree.setCheckedKeys([])
    },
    async hSubmit() {
      // 获取tree中选中的节点 组件库 提供方法 getCheckedKeys
      const permIds = this.$refs.tree.getCheckedKeys()
      const res = await assignPerm({ id: this.roleId, permIds })
      console.log('保存角色的权限', res)
      this.$message.success('保存角色权限成功')
      //   关闭弹层
      this.hCancel()
    }
  }
}
</script>
